"""
用户模型
映射数据库users表
"""
from sqlalchemy import Column, Integer, String, Date, DateTime, Enum as SQLEnum
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import relationship
import enum
from datetime import datetime
from passlib.context import CryptContext

from app.models.base import BaseModel


class UserRole(enum.Enum):
    """用户角色枚举"""
    USER = "user"
    ADMIN = "admin"


# 密码加密上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


class User(BaseModel):
    """
    用户模型类
    对应数据库中的users表
    """
    
    __tablename__ = "users"
    
    id = Column(
        Integer, 
        primary_key=True, 
        autoincrement=True,
        comment='用户ID'
    )
    
    username = Column(
        String(50), 
        nullable=False, 
        unique=True,
        index=True,
        comment='用户名'
    )
    
    password = Column(
        String(255), 
        nullable=False,
        comment='密码'
    )
    
    email = Column(
        String(100), 
        nullable=False, 
        unique=True,
        index=True,
        comment='邮箱'
    )
    
    avatar = Column(
        String(255), 
        nullable=True,
        comment='头像URL'
    )
    
    nickname = Column(
        String(50), 
        nullable=True,
        comment='昵称'
    )
    
    status = Column(
        TINYINT, 
        nullable=False, 
        default=1,
        comment='状态：1-正常，0-禁用'
    )
    
    role = Column(
        SQLEnum(UserRole), 
        nullable=False, 
        default=UserRole.USER,
        comment='用户角色'
    )
    
    login_attempts = Column(
        Integer, 
        nullable=False, 
        default=0,
        comment='登录尝试次数'
    )
    
    lock_until = Column(
        DateTime, 
        nullable=True,
        comment='账号锁定时间'
    )
    
    deleted_at = Column(
        DateTime, 
        nullable=True,
        index=True,
        comment='删除时间（软删除）'
    )
    
    # 关系
    videos = relationship('Video', back_populates='user')
    comments = relationship('Comment', back_populates='user')
    likes = relationship('Like', back_populates='user')
    favorites = relationship('Favorite', back_populates='user')
    
    last_login_ip = Column(
        String(50), 
        nullable=True,
        comment='最后登录IP'
    )
    
    last_login_at = Column(
        DateTime, 
        nullable=True,
        comment='最后登录时间'
    )
    
    login_count = Column(
        Integer, 
        nullable=False, 
        default=0,
        comment='登录次数'
    )
    
    password_reset_token = Column(
        String(200), 
        nullable=True,
        comment='密码重置令牌'
    )
    
    password_reset_expires = Column(
        Integer, 
        nullable=True,
        comment='密码重置过期时间戳'
    )
    
    def set_password(self, password: str):
        """
        设置密码（自动加密）
        
        Args:
            password: 明文密码
        """
        if password:
            self.password = pwd_context.hash(password)
    
    def verify_password(self, password: str) -> bool:
        """
        验证密码
        
        Args:
            password: 明文密码
            
        Returns:
            bool: 密码是否正确
        """
        return pwd_context.verify(password, self.password)
    
    def is_locked(self) -> bool:
        """
        检查用户是否被锁定
        
        Returns:
            bool: 是否锁定
        """
        if self.lock_until:
            return datetime.utcnow() < self.lock_until
        return False